package com.example.administrator.commonlibrary.welcomepage;



import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.example.administrator.commonlibrary.R;
import com.example.administrator.commonlibrary.bean.TabEntityBean;
import com.example.administrator.commonlibrary.bese.BaseAppliction;
import com.example.administrator.commonlibrary.bese.BaseFragment;
import com.example.administrator.commonlibrary.bese.BaseViewActivity;
import com.example.administrator.commonlibrary.contract.activity.MaiAcivityContract;

import com.example.administrator.commonlibrary.definedview.extension.ControlScrollViewPager;
import com.example.administrator.commonlibrary.welcomepage.presenter.MaiActivityPresenter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.umeng.analytics.MobclickAgent;


import java.util.ArrayList;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class MainActivity extends BaseViewActivity<MaiAcivityContract.Presenter> implements MaiAcivityContract.View {

    private long exitTime;

    CommonTabLayout tabLayout;
    private ControlScrollViewPager viewPager;
    // 记录上次点击（显示）的位置
    private int lastItemSelected = 0;
    private MaiActivityPresenter presenter;
    private final String ONE_FRAGMENT = "one_fragment";
    private final String TWO_FRAGMENT = "two_fragment";
    private final String THREE_FRAGMENT = "three_fragment";
    private final String FOUR_FRAGMENT = "four_fragment";
    private final String FIVE_FRAGMENT = "five_fragment";
    private final String SELETE_INDEX = "lastItemSelected";
    private List<BaseFragment> fragments = new ArrayList<>();
    private String[] mTitles = {"首页", "消息", "联系人", "更多","更多"};
    private int[] mIconUnselectIds = {
            R.drawable.tab_home_unselect, R.drawable.tab_speech_unselect,
            R.drawable.tab_contact_unselect, R.drawable.tab_more_unselect,R.drawable.tab_more_unselect};
    private int[] mIconSelectIds = {
            R.drawable.tab_home_select, R.drawable.tab_speech_select,
            R.drawable.tab_contact_select, R.drawable.tab_more_select,R.drawable.tab_more_select};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();


    @Override
    protected void myOnCreate() {
      MainActivityPermissionsDispatcher.setShowPermissionWithPermissionCheck(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tabLayout = findViewById(R.id.last_tabLayout);
         viewPager = findViewById(R.id.vp_content);
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntityBean(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        List<BaseFragment> newsFragment = BaseAppliction.getBaseAppliction().getNewsFragment();
        fragments.addAll(newsFragment);
        if (savedInstanceState != null) {
            lastItemSelected = savedInstanceState.getInt(SELETE_INDEX, 0);
            /*获取保存的fragment  没有的话返回null*/
            BaseFragment fragment = (BaseFragment) getSupportFragmentManager().getFragment(savedInstanceState, ONE_FRAGMENT);
            BaseFragment fragment1 = (BaseFragment) getSupportFragmentManager().getFragment(savedInstanceState, TWO_FRAGMENT);
            BaseFragment fragment2 = (BaseFragment) getSupportFragmentManager().getFragment(savedInstanceState, THREE_FRAGMENT);
            BaseFragment fragment3 = (BaseFragment) getSupportFragmentManager().getFragment(savedInstanceState, FOUR_FRAGMENT);
            BaseFragment fragment4 = (BaseFragment) getSupportFragmentManager().getFragment(savedInstanceState, FIVE_FRAGMENT);

            if (fragment != null) {
                fragments.remove(0);
                fragments.add(0, fragment);
            }
            if (fragment1 != null) {
                fragments.remove(1);
                fragments.add(1, fragment1);
            }
            if (fragment2 != null) {
                fragments.remove(2);
                fragments.add(2, fragment2);
            }
            if (fragment3 != null) {
                fragments.remove(3);
                fragments.add(3, fragment3);
            }
            if (fragment4 != null) {
                fragments.remove(4);
                fragments.add(4, fragment4);
            }
        }
        tabLayout.setTabData(mTabEntities);
        viewPager.setAdapter(getSupportFragmentManager(),false,fragments,tabLayout);

    }

    @Override
    protected int onLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected MaiAcivityContract.Presenter initPresenter() {
        presenter = new MaiActivityPresenter();
        return presenter;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELETE_INDEX, lastItemSelected);
        if (fragments.get(0) != null && fragments.get(0).isAdded()) {
            getSupportFragmentManager().putFragment(outState, ONE_FRAGMENT, fragments.get(0));
        }
        if (fragments.get(1) != null && fragments.get(1).isAdded()) {
            getSupportFragmentManager().putFragment(outState, TWO_FRAGMENT, fragments.get(1));
        }
        if (fragments.get(2) != null && fragments.get(2).isAdded()) {
            getSupportFragmentManager().putFragment(outState, THREE_FRAGMENT, fragments.get(2));
        }
        if (fragments.get(3) != null && fragments.get(3).isAdded()) {
            getSupportFragmentManager().putFragment(outState, FOUR_FRAGMENT, fragments.get(3));
        }
        if (fragments.get(4) != null && fragments.get(4).isAdded()) {
            getSupportFragmentManager().putFragment(outState, FIVE_FRAGMENT, fragments.get(4));
        }
        super.onSaveInstanceState(outState);
    }



    /*
     * 返回键退出应用
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                //如果开发者调用kill或者exit之类的方法杀死进程，请务必在此之前调用onKillProcess方法，用来保存统计数据。
                MobclickAgent.onKillProcess(BaseAppliction.getBaseAppliction());
                System.exit(0);
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ARouter.getInstance().destroy();//关闭路由
    }

    @Override
    protected String setPageTitle() {
        return "程序入口";
    }

    //但特殊权限Manifest.permission.SYSTEM_ALERT_WINDOW和Manifest.permission.WRITE_SETTINGS就有点改动，
    // 但改动不大，只是把onRequestPermissionsResult中权限回调的写在onActivityResult中。
  @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_LOGS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.SET_DEBUG_APP,
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.WRITE_APN_SETTINGS})
    void setShowPermission(){

    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }
}
